/**
 * $RCSfile$
 * $Revision: 11691 $
 * $Date: 2010-05-01 11:42:07 -0500 (Sat, 01 May 2010) $
 *
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jawa.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.jawa.database.DbConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 属性操作类.属性值存储在数据库中.
 * 
 */
public class JawaProperties implements Map<String, String> {

	private static final Logger Log = LoggerFactory
			.getLogger(JawaProperties.class);

	private Map<String, String> properties;

	private static final String LOAD_PROPERTIES = "SELECT propname, propvalue FROM jawa_property";
	private static final String INSERT_PROPERTY = "INSERT INTO jawa_property(propname, propvalue) VALUES(?,?)";
	private static final String UPDATE_PROPERTY = "UPDATE jawa_property SET propvalue=? WHERE propname=?";
	private static final String DELETE_PROPERTY = "DELETE FROM jawa_property WHERE propname LIKE ?";

	private static class JivePropertyHolder {
		private static final JawaProperties instance = new JawaProperties();
		static {
			instance.init();
		}
	}

	/**
	 * 
	 * @return 属性操作单一实例.
	 */
	public static JawaProperties getInstance() {
		return JivePropertyHolder.instance;
	}

	private JawaProperties() {
	}

	/**
	 * 这个方法允许重新将数据库的属性加载到内在中去.
	 */
	public void init() {
		if (properties == null) {
			properties = new ConcurrentHashMap<String, String>();
		} else {
			properties.clear();
		}

		loadProperties();
	}

	public int size() {
		return properties.size();
	}

	public void clear() {
		throw new UnsupportedOperationException();
	}

	public boolean isEmpty() {
		return properties.isEmpty();
	}

	public boolean containsKey(Object key) {
		return properties.containsKey(key);
	}

	public boolean containsValue(Object value) {
		return properties.containsValue(value);
	}

	public Collection<String> values() {
		return Collections.unmodifiableCollection(properties.values());
	}

	public void putAll(Map<? extends String, ? extends String> t) {
		for (Map.Entry<? extends String, ? extends String> entry : t.entrySet()) {
			put(entry.getKey(), entry.getValue());
		}
	}

	public Set<Map.Entry<String, String>> entrySet() {
		return Collections.unmodifiableSet(properties.entrySet());
	}

	public Set<String> keySet() {
		return Collections.unmodifiableSet(properties.keySet());
	}

	public String get(Object key) {
		return properties.get(key);
	}

	/**
	 * 返回父属性下的所有子属性. 例如存在以下属性 <tt>X.Y.A</tt>, <tt>X.Y.B</tt>, and <tt>X.Y.C</tt>
	 * , 调用 <tt>X.Y</tt> 将返回<tt>X.Y.A</tt>, <tt>X.Y.B</tt>, and <tt>X.Y.C</tt>.
	 * 但是本属性不会返回子属性的子属性.
	 * 
	 * @param parentKey
	 *            父属性名称.
	 * @return 当前父属性的所有子属性名称.
	 */
	public Collection<String> getChildrenNames(String parentKey) {
		Collection<String> results = new HashSet<String>();
		for (String key : properties.keySet()) {
			if (key.startsWith(parentKey + ".")) {
				if (key.equals(parentKey)) {
					continue;
				}
				int dotIndex = key.indexOf(".", parentKey.length() + 1);
				if (dotIndex < 1) {
					if (!results.contains(key)) {
						results.add(key);
					}
				} else {
					String name = parentKey
							+ key.substring(parentKey.length(), dotIndex);
					results.add(name);
				}
			}
		}
		return results;
	}

	/**
	 * 返回所有的属性名称.
	 * 
	 * @return all property names.
	 */
	public Collection<String> getPropertyNames() {
		return properties.keySet();
	}

	public String remove(Object key) {
		String value;
		synchronized (this) {
			value = properties.remove(key);
			// Also remove any children.
			Collection<String> propNames = getPropertyNames();
			for (String name : propNames) {
				if (name.startsWith((String) key)) {
					properties.remove(name);
				}
			}
			deleteProperty((String) key);
		}

		return value;
	}

	/**
	 * 只在内存中操作，不影响数据库.
	 * 
	 * @param key
	 */
	void localRemove(String key) {
		properties.remove(key);
		// 同时删除所有子属性.
		Collection<String> propNames = getPropertyNames();
		for (String name : propNames) {
			if (name.startsWith(key)) {
				properties.remove(name);
			}
		}

	}

	/**
	 * 
	 */
	public String put(String key, String value) {
		if (value == null) {
			// 相当于删除.
			return remove(key);
		}
		if (key == null) {
			throw new NullPointerException("Key 不可以为空. Key=" + key + ", value="
					+ value);
		}
		if (key.endsWith(".")) {
			key = key.substring(0, key.length() - 1);
		}
		key = key.trim();
		String result;
		synchronized (this) {
			if (properties.containsKey(key)) {
				if (!properties.get(key).equals(value)) {
					updateProperty(key, value);
				}
			} else {
				insertProperty(key, value);
			}

			result = properties.put(key, value);
		}

		return result;
	}

	void localPut(String key, String value) {
		properties.put(key, value);

	}

	public String getProperty(String name, String defaultValue) {
		String value = properties.get(name);
		if (value != null) {
			return value;
		} else {
			return defaultValue;
		}
	}

	public boolean getBooleanProperty(String name) {
		return Boolean.valueOf(get(name));
	}

	public boolean getBooleanProperty(String name, boolean defaultValue) {
		String value = get(name);
		if (value != null) {
			return Boolean.valueOf(value);
		} else {
			return defaultValue;
		}
	}

	private void insertProperty(String name, String value) {
		Connection con = null;
		PreparedStatement pstmt = null;
		try {
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement(INSERT_PROPERTY);
			pstmt.setString(1, name);
			pstmt.setString(2, value);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			Log.error(e.getMessage(), e);
		} finally {
			DbConnectionManager.closeConnection(pstmt, con);
		}
	}

	private void updateProperty(String name, String value) {
		Connection con = null;
		PreparedStatement pstmt = null;
		try {
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement(UPDATE_PROPERTY);
			pstmt.setString(1, value);
			pstmt.setString(2, name);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			Log.error(e.getMessage(), e);
		} finally {
			DbConnectionManager.closeConnection(pstmt, con);
		}
	}

	private void deleteProperty(String name) {
		Connection con = null;
		PreparedStatement pstmt = null;
		try {
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement(DELETE_PROPERTY);
			pstmt.setString(1, name + "%");
			pstmt.executeUpdate();
		} catch (SQLException e) {
			Log.error(e.getMessage(), e);
		} finally {
			DbConnectionManager.closeConnection(pstmt, con);
		}
	}

	private void loadProperties() {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement(LOAD_PROPERTIES);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				String name = rs.getString(1);
				String value = rs.getString(2);
				properties.put(name, value);
			}
		} catch (Exception e) {
			Log.error(e.getMessage(), e);
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
	}
}